from celery import current_app
from flask import Blueprint, jsonify, g
from flask_restful import Api, Resource, marshal,reqparse
from models.my_fields import channel_fields, news_fields, user_fields, comment_fields

from apps.user import require_login
from apps.user import login_gz

from models.model import Channel, User, db, News, Comment

news_bp = Blueprint("news_bp", __name__, url_prefix="/news")

api = Api(news_bp)

@news_bp.before_request
def login_gz2():
    login_gz()


# 频道的类试图
class ChannelView(Resource):
    def get(self):
        # 获取所有频道
        channel_all = Channel.query.filter(Channel.is_show == True).order_by(Channel.score.desc()).all()
        print(channel_all)
        channel_json = marshal(channel_all, channel_fields)

        return jsonify({
            "code": 200,
            "msg": "频道获取成功",
            "channel": channel_json,
        })



#  用户频道试图
class UserChannelView(Resource):
    @require_login
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('cid',type=int,required=True)
        args = req.parse_args()

        cid = (args['cid'])    #  频道ID
        uid = g.user['user_id']

        #  判断一下数据库是否已经有这条数据了
        user_info = User.query.filter(User.uid == uid).first()
        print(user_info.channels)
        #  需要判断当前ID是否在频道里面

        #  当前数据库有没有要添加的数据
        channel_info = Channel.query.filter(Channel.cid == cid).first()

        if channel_info in user_info.channels:
            return jsonify({
                'code':200,
                'msg':'已存在'
            })

        print(channel_info)
        user_info.channels.append(channel_info)
        db.session.commit()
        return jsonify({
            'code':200,
            'msg':'添加成功'
        })

    #  删除用户频道
    @require_login
    def delete(self):
        req = reqparse.RequestParser()
        req.add_argument('cid', type=int, required=True)
        args = req.parse_args()

        cid = (args['cid'])  # 频道ID
        uid = g.user['user_id']

        user_info = User.query.filter(User.uid == uid).first()
        channel_info = Channel.query.filter(Channel.cid == cid).first()

        if channel_info in user_info.channels:
            return jsonify({
                'code':400,
                'msg':'已经不存在'
            })
        user_info.channels.remove(channel_info)
        db.session.commit()

        return jsonify({
            'code':200,
            'msg':'删除成功'
        })



    @require_login
    def get(self):
        uid = g.user['user_id']

        #  通过uid查询当前用户信息
        user_info = User.query.filter(User.uid == uid).first()
        user_channel = user_info.channels

        c_json = marshal(user_channel,channel_fields)

        return jsonify({
            'code':200,
            'msg':'获取成功',
            'channels': c_json
        })

#   资讯类试图
class NewsView(Resource):
    def get(self):
        req = reqparse.RequestParser()
        req.add_argument('page',type=int,default=1)
        req.add_argument('limit',type=int,default=10)

        args = req.parse_args()

        begin = (args['page'] - 1)*args['limit']

        news_list = News.query.order_by(News.read_count.desc()).offset(begin).limit(args['limit']).all()

        return jsonify({
            'code':200,
            'msg':'OK',
            'news':marshal(news_list,news_fields)
        })

#  频道下的文章
class ChannelNewsViwe(Resource):
    def get(self,cid):
        # channel_info = Channel.query.filter(Channel.cid == cid).first()
        #
        # #  通过频道信息获取频道资讯
        # news_list = channel_info.news
        req = reqparse.RequestParser()
        req.add_argument('page',type=int,default=1)
        req.add_argument('limit',type=int,default=10)

        args = req.parse_args()

        begin = (args['page'] - 1) * args['limit']


        news_list = News.query.filter(News.channel_id == cid).offset(begin).limit(args['limit']).all()
        return jsonify({
            'code':200,
            'msg':'当前频道获取成功',
            'news':marshal(news_list,news_fields)
        })

#  资讯类试图
class NewsViews(Resource):
    def get(self,nid):
        news_info = News.query.filter(News.nid == nid).first()
        news_json = marshal(news_info,news_fields)

        user_json = marshal(news_json.user,user_fields)
        #  获取作者信息

        return jsonify({
            'code':200,
            'msg':'获取资讯详情成功',
            'info':{
                'news':news_json,
                'user':user_json
            }
        })

#  收藏的试图
class Collect(Resource):
    @require_login
    def post(self,nid):
        uid = g.user['user_id']

        #  判断当前ID 是否存在表里
        collect_info = Collect.query.filter(Collect.user_id == uid).filter(Collect.news_id == nid).first()
        #  如果在，把他的is_delete状态改为0
        if collect_info:
            collect_info.is_delete = 0
            db.session.commit()
            return jsonify({
                'code':200,
                'msg':'收藏成功'
            })
        #  如果不在，就写入一条数据，并且is_delete为0
        c = Collect(user_id = uid,news_id=nid,is_delete=0)
        db.session.add(c)
        db.session.commit()
        return jsonify({
            'code': 200,
            'msg': '收藏成功'
        })

    @require_login
    def delete(self,nid):
        uid = g.user['user_id']

        collect_info = Collect.query.filter(Collect.news_id == nid).filter(Collect.user_id == nid).first()

        if not collect_info:
            return jsonify({
                'code':400,
                'msg':'还没有收藏',
            })
        if collect_info.is_delete == 1:
            return jsonify({
                'code': 400,
                'msg': '还没有收藏',
            })
        collect_info.is_delete = 1
        db.session.commit()
        return jsonify({
            'code': 200,
            'msg': '取消收藏成功',
        })

    @require_login
    def put(self,nid):
        uid = g.user['user_id']
        collect_info = Collect.query.filter(Collect.user_id == uid).filter(Collect.news_id == nid).first()

        if not collect_info:
            c = Collect(news_id = nid ,user_id = nid ,is_delete = 0)
            db.session.add(c)
            db.session.commit()
            return jsonify({
                'code':200,
                'msg':'收藏成功'
            })
        if collect_info.is_delete == 0:
            collect_info.is_delete = 1
            db.session.commit()
            return jsonify({
                'code': 400,
                'msg': '取消收藏成功'
            })
        collect_info.is_delete = 1
        db.session.commit()
        return jsonify({
            'code': 200,
            'msg': '收藏成功'
        })

#  评论的试图
class CommentView(Resource):
    @require_login
    def post(self):
        user_id = g.user['user_id']
        req = reqparse.RequestParser()
        req.add_argument('nid',type=int,required=True)
        req.add_argument('content', type=str, required=True)

        args = req.parse_args()
        #  把数据写入数据库
        c = Comment(user_id=user_id,news_id=args['nid'],content=args['content'])
        db.session.add(c)
        db.session.commit()
        return jsonify({
            'code':200,
            'msg':'评论成功',
        })

    def get(self):
        req = reqparse.RequestParser()
        req.add_argument('nid',type=int,required=True)
        args = req.parse_args()

        comment_list = Comment.query.filter(Comment.news_id == args['nid']).filter(Comment.status==0).order_by(
           Comment.is_top.desc()).all()
        list = []
        for comm in comment_list:
            comm_json = marshal(comm, comment_fields)
            user_json = marshal(comm.user,user_fields)
            user_json['img'] = current_app.config["QINIU_HOST"]+user_json['img']
            list.append({
                'comm':comm_json,
                'user':user_json,
            })
        return jsonify({
            'code':200,
            'msg':'评论获取成功',
            'list':list,
        })

    def delete(self):
        user_id = g.user['user_id']
        req = reqparse.RequestParser()
        req.add_argument('cmid', type=int, required=True)
        args = req.parse_args()
        comment_info = Comment.query.filter(Comment.cmid == args['nid']).first()
        if not comment_info:
            return jsonify({
                'code':400,
                'msg':'评论不存在'
            })
        if comment_info.user_id != user_id:
            return jsonify({
                'code':400,
                'msg':'没有权限'
            })
        comment_info.status = 1
        db.session.commit()

        return jsonify({
            'code':200,
            'msg':'删除成功'
        })


api.add_resource(ChannelView, "/channel")

 # 用户频道路由
api.add_resource(UserChannelView,'/channel/user')
#  资讯路由
api.add_resource(NewsView,'/channel/news')
#  推荐资讯路由
api.add_resource(ChannelNewsViwe,'/channel/<int:cid>/')
#  资讯详情路由
api.add_resource(NewsViews,'/channel/<int:nid>/')
#  收藏
api.add_resource(Collect,'/channel/<int:uid>/')
#  评论
api.add_resource(CommentView,'/channel/comment')


